<template>
  <div >
    <van-nav-bar title="发布文章"  class="page-nav-bar"/>
   <template v-if="token">
      <van-form @submit="onSubmit">
        <van-field
          v-model="atctitle"
          name="title"
          label="文章标题"
          placeholder="文章标题"
          :rules="[{ required: true, message: '请填写文章标题' }]"
        />
        <van-field
          readonly
          clickable
          name="tags"
          :value="tagName"
          label="文章标签"
          placeholder="点击选择文章标签"
          @click="showTagsPicker = true"
          :rules="[{ required: true, message: '请选择标签' }]"
        />
        <van-popup v-model="showTagsPicker" position="bottom">
          <van-picker
            show-toolbar
            :columns="tagsList"
            @confirm="onConfirm"
            @cancel="showTagsPicker = false"
          />
        </van-popup>
        <van-field
          readonly
          clickable
          name="cate"
          :value="cateName"
          :rules="[{ required: true, message: '请选择分类' }]"
          label="文章分类"
          placeholder="点击选择文章分类"
          @click="showCatesPicker = true"
        />
        <van-popup v-model="showCatesPicker" position="bottom">
          <van-picker
            show-toolbar
            :columns="cateList"
            @confirm="onCatesConfirm"
            @cancel="showCatesPicker = false"
          />
        </van-popup>

        <van-field
          name="uploader"
          label="文件上传"
          :rules="[{ required: true, message: '请上传封面图片' }]"
        >
          <template #input>
            <van-uploader
              v-model="uploader"
              max-count="1"
              :after-read="afterRead"
            />
          </template>
        </van-field>
        <van-field
          v-model="content"
          name="content"
          rows="5"
          autosize
          label="文章内容"
          type="textarea"
          placeholder="请输入文章内容"
          :rules="[{ required: true, message: '请输入文章内容' }]"
        />
        <div class="btns" style="margin: 16px">
          <van-button
            block
            type="primary"
            native-type="submit"
            @click="status = 2"
            >提交</van-button
          >
          <van-button block type="info" native-type="submit" @click="status = 1"
            >存草稿</van-button
          >
          <van-button
            block
            type="danger"
            native-type="button"
            @click="clearForm"
            >重置</van-button
          >
        </div>
      </van-form>
    </template>
   
    <!-- 未登录的样子 -->
    <div v-else>
      <van-empty  image="error" @click="add" />
      <van-row type="flex" justify="center">
       <router-link to="/login">请登录</router-link>
      </van-row>
    </div>
    
  </div>
</template>

<script>
import { postArticle, uploadImage } from "../api/add";
import { getindex } from "../api/index";
import { mapGetters } from "vuex";
import { getUserInfo } from "../api/login";
export default {
  data() {
    return {
      atctitle: '',
      tagName: '',
      cateName: '',
      tagsList: [],
      cateList: [],
      allCate: [],
      showTagsPicker: false,
      showCatesPicker: false,
      uploader: [],
      content: '',
      status: '',
      author: '',
    };
  },
  computed: {
    // 通过计算属性取出对应分类id
    cateid() {
      return (
        this.cateName &&
        this.allCate.find((item) => item.catename === this.cateName).id
      );
    },
    // ...mapState(["token"]),
    ...mapGetters(['token'])
  },
  methods: {
    // 判断是否含有token,没有就直接return出去，有则通过个人信息取出用户名
    loadUserName() {
      if (!this.token) {
        return;
      }
      getUserInfo(this.token).then((resp) => {
        this.author = resp.data.data.userInfo.username;
      });
    },
    // 标签页的折叠页面
    onConfirm(tagName) {
      this.tagName = tagName;
      this.showTagsPicker = false;
    },
    // 分类页的折叠页面
    onCatesConfirm(cateName) {
      this.cateName = cateName;
      this.showCatesPicker = false;
    },
    //提交表单
    onSubmit(value) {
      const { title, content, tags } = value;
      postArticle(
        {
          title,//标题
          content,//正文内容
          tags,//标签
          cateid: this.cateid,//分类id
          pic: this.uploader[0].url,//图片地址
          author: this.author,//作者姓名
          status: this.status,//文章状态
        },
        this.token
      ).then(() => {
        let successMsg = "";
        if (this.status === 2) {
          successMsg = "已发布";
        } else if (this.status === 1) {
          successMsg = "已存为草稿";
        }
        this.$toast.success(successMsg);
        this.clearForm();
      });
    },
    clearForm() {
      this.articleTitle = '';
      this.tagName = '';
      this.cateName = '';
      this.content = '';
      this.status = '';
      this.uploader = [];
    },
    loadGlobalData() {
      //获取首页资料
      getindex().then((resp) => {
        // console.log(resp);
        // 标签所在位置
        // 遍历数组，然后取出需要的数据放入对应数组
        resp.data.data.allTag.forEach((tag) => {
          this.tagsList.push(tag.tagname);
        });
        // 分类所在位置
        this.allCate = resp.data.data.allCate;
        // 遍历数组，然后取出需要的数据放入对应数组
        resp.data.data.allCate.forEach((cate) => {
          this.cateList.push(cate.catename);
        });
      });
    },
    //获取提交图片信息
    afterRead(file) {
      console.log(file.file);
      const data = new FormData();
      data.append("file", file.file);
      uploadImage(data).then((resp) => {
        console.log(resp);
        this.uploader[0].url = resp.data.data.savePath;
      });
    },
  },

  created() {
    this.loadGlobalData();
    this.loadUserName();
  },
};
</script>

<style lang="less" scope>
.btns {
  display: flex;
  justify-content: space-between;
  .van-button {
    width: 100px;
  }
}
// .qw {
//   margin: 25px;
// }
</style>

